package com.bowen.spike.interceptor;

import com.alibaba.fastjson2.JSON;
import com.bowen.spike.common.Result;
import com.bowen.spike.context.UserContext;
import com.bowen.spike.my_enum.ResultCode;
import com.bowen.spike.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录处理器
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    /**
     * 权限校验处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        long userId = JwtUtil.parseToken(token);

        // 解析token失败或过期返回-1
        if (userId == JwtUtil.PARSING_FAILED) {
            writeAuthorizationFailed(response);
            return false;
        }

        UserContext.saveUserId(userId);
        return true;
    }

    /**
     * 封装未授权的返回结果信息
     */
    private void writeAuthorizationFailed(HttpServletResponse response) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        Result<Void> failed = Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
        String body = JSON.toJSONString(failed);
        try {
            PrintWriter writer = response.getWriter();
            writer.write(body);
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 清理 threadLocal
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}
